package com.growthsee.rider.utils.ci;

import com.growthsee.common.utils.uuid.UUID;
import com.growthsee.rider.domain.view.RiderAttachmentView;
import com.growthsee.rider.utils.BasicPathUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.tencent.cloud.CosStsClient;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.TreeMap;

public class QCloudCosUtils {

    /**
     * 上传File类型的文件
     * @param file
     * @return 上传文件在存储桶的链接
     */
    public static   String upload(File file) {
        String newFileName = generateUniqueName(file.getName());  //生成唯一文件名
        String key = BasicPathUtil.getPrefix()+newFileName;  //文件在存储桶中的key
        COSClient cosClient=null;  //声明客户端
        try {
            cosClient =getCOSClient();
            PutObjectRequest putObjectRequest = new PutObjectRequest(BasicPathUtil.getBucketName(), key, file);  //创建存储对象的请求
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); //执行上传并返回结果信息
            return BasicPathUtil.getCloudurl()+key;
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return null;
    }

    /**
     * upload()重载方法
     * @param multipartFile
     * @return 上传文件在存储桶的链接
     */
    public static RiderAttachmentView upload(MultipartFile multipartFile) {
        String newFileName = generateUniqueName(multipartFile.getOriginalFilename());  //生成唯一文件名
        String key = BasicPathUtil.getPrefix()+newFileName; //文件在存储桶中的key
        //声明客户端
        COSClient cosClient = null;
        File file = null;
        try {
            file = File.createTempFile("temp",null);   //生成临时文件
            multipartFile.transferTo(file);   //将MultipartFile类型转为File类型
            cosClient = getCOSClient();
            PutObjectRequest putObjectRequest = new PutObjectRequest(BasicPathUtil.getBucketName(), key, file); //执行上传并返回结果信息
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //数据入库
            String fileName = multipartFile.getOriginalFilename();
            RiderAttachmentView riderAttachmentView = new RiderAttachmentView();
            riderAttachmentView.setName(fileName.substring(0,fileName.lastIndexOf(".")));
            riderAttachmentView.setSize(multipartFile.getSize());
            riderAttachmentView.setKeyValue(key);
            riderAttachmentView.setContentType(multipartFile.getContentType());
            riderAttachmentView.setSuffix(fileName.substring(fileName.lastIndexOf(".") + 1));
            riderAttachmentView.setUrl("https://"+BasicPathUtil.getBucketName()+".cos."+BasicPathUtil.getRegion()+".myqcloud.com/"+key);
            return riderAttachmentView;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return null;
    }

    public static COSClient getCOSClient(){
        COSCredentials cosCredentials = new BasicCOSCredentials(BasicPathUtil.getSecretId(), BasicPathUtil.getSecretKey());  //设置bucket的区域
        ClientConfig clientConfig = new ClientConfig(new Region(BasicPathUtil.getRegion()));  //生成cos客户端
        COSClient cosClient = new COSClient(cosCredentials, clientConfig);  //创建存储对象的请求
        return cosClient;
    }

    /**
     * 根据UUID生成唯一文件名
     * @param originalName
     * @return
     */
    public static String generateUniqueName(String originalName) {
        return UUID.randomUUID() + originalName.substring(originalName.lastIndexOf("."));
    }

    public static JSONObject getTemporaryKey() {
        TreeMap<String, Object> config = new TreeMap<String, Object>();
        try {
            // 替换为您的 SecretId
            config.put("SecretId", BasicPathUtil.getSecretId());
            // 替换为您的 SecretKey
            config.put("SecretKey", BasicPathUtil.getSecretKey());

            // 临时密钥有效时长，单位是秒，默认1800秒，目前主账号最长2小时（即7200秒），子账号最长36小时（即129600秒）
            config.put("durationSeconds", 1800);

            // 换成您的 bucket
            config.put("bucket", BasicPathUtil.getBucketName());
            // 换成 bucket 所在地区
            config.put("region",  BasicPathUtil.getRegion());

            // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子：a.jpg 或者 a/* 或者 * 。
            // 如果填写了“*”，将允许用户访问所有资源；除非业务需要，否则请按照最小权限原则授予用户相应的访问权限范围。
            config.put("allowPrefix", "*");

            // 密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[] {
                    // 简单上传
                    "name/cos:PutObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);

            JSONObject credential = CosStsClient.getCredential(config);
            //成功返回临时密钥信息，如下打印密钥信息
            System.out.println(credential);
            return credential;
        } catch (Exception e) {
            //失败抛出异常
            throw new IllegalArgumentException("no valid secret !");
        }
    }

}
